package com.lb.shopguide.ui.fragment.boss;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterPickCash;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.MerchantBean;
import com.lb.shopguide.entity.PickCashRecordBean;
import com.lb.shopguide.event.boss.ChargeInEvent;
import com.lb.shopguide.event.boss.ChargeOutEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.view.ClearTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/12/26.
 */

public class FragmentFinanceManage extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.ctb)
    ClearTitleBar ctb;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_froze_money)
    TextView tvFrozeMoney;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private ArrayList<PickCashRecordBean> mPickCashList;
    private AdapterPickCash mAdapterPickCash;

    private MerchantBean merchantBean;



    public static FragmentFinanceManage newInstance(MerchantBean merchantBean) {
        FragmentFinanceManage fragmentFinanceManage = new FragmentFinanceManage();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.MERCHANT_BEAN, merchantBean);
        fragmentFinanceManage.setArguments(bundle);
        return fragmentFinanceManage;
    }

    public static FragmentFinanceManage newInstance() {
        return new FragmentFinanceManage();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_finance_manage;
    }

    @Override
    public void initData() {
        mPickCashList = new ArrayList<>();
        sendRequestGetFinanceList();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.MERCHANT_BEAN)) {
            merchantBean = (MerchantBean) bundle.getSerializable(AppConstant.MERCHANT_BEAN);
        } else {
            sendRequestGetMerchantInfo();
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {

        ctb.setTvTitle("财务管理");
        ctb.setLeftImageSrc(R.drawable.iv_back);

        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view_boss, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无记录");
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        noDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapterPickCash = new AdapterPickCash(R.layout.item_pick_cash, mPickCashList);
        mRecyclerView.setAdapter(mAdapterPickCash);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).marginProvider(mAdapterPickCash).paintProvider(mAdapterPickCash).build());
        ctb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mAdapterPickCash.loadMoreComplete();
    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }


    private void sendRequestGetFinanceList() {
        mPickCashList = new ArrayList<>();
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        String accountBalance = jsonObject.getString("accountBalance");// 总资产
                        String frozenBond = jsonObject.getString("frozenBond"); // 冻结金额
                        bindMoney(frozenBond, accountBalance);
                        if (jsonObject.has("pickCashRecord")) {
                            JSONArray jsonArray = jsonObject.getJSONArray("pickCashRecord");
                            if (jsonArray.length() != 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    PickCashRecordBean pickCashRecordBean = JsonUtil.getGson().fromJson(jsonArray.getString(i), PickCashRecordBean.class);
                                    mPickCashList.add(pickCashRecordBean);
                                }
                                mAdapterPickCash.setNewData(mPickCashList);
                            } else {
                                bindEmpty();
                            }
                        } else {
                            bindEmpty();
                        }
                        finishRefresh();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodBoss.getFinanceList(new SimpleLbObserver(listener,otherListener),this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestGetMerchantInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    merchantBean = (MerchantBean) JsonUtil.getObject(response.getReturnContent(), MerchantBean.class);
                }
            }
        };
        ApiMethodBoss.getMerchantInfo(new SimpleLbObserver(listener,otherListener),this,FragmentEvent.DESTROY_VIEW);
    }

    @Override
    public String getPageTag() {
        return FragmentFinanceManage.class.getName();
    }

    @OnClick(R.id.layout_charge)
    void charge() {
        start(FragmentChargeInMoney.newInstance());
    }

    @OnClick(R.id.layout_withdraw)
    void withDraw() {
        start(FragmentChargeOutMoney.newInstance(merchantBean.getReceiveAccount()));
    }

    private void bindMoney(String frozeMoney, String totalMoney) {
        tvFrozeMoney.setText("冻结金额：" + frozeMoney);
        tvTotalMoney.setText(totalMoney);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshFinance(ChargeOutEvent event) {
        sendRequestGetFinanceList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshFinance(ChargeInEvent event) {
        sendRequestGetFinanceList();
    }


    private void bindEmpty() {
        mPickCashList.clear();
        mAdapterPickCash.setNewData(mPickCashList);

        mNoData = true;
        onRefresh();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void onRefresh() {
        mAdapterPickCash.setEnableLoadMore(false);
        if (mError) {
            mAdapterPickCash.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterPickCash.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    public void refresh() {
        sendRequestGetFinanceList();
    }
}
